/**
 * Crazy Table Tips
 *  License by CrazyYi.
 *  v1.0.0 20200211
 *
 *
 */
layui.define(['jquery', 'layer', 'crazyQuery', 'crazyData', 'crazyTool'], function (exports) {
    const MOD_NAME = 'crazyTips'
    const TABLE_CELL = '.layui-table-cell'

    const $ = layui.jquery,
        $Data = layui.crazyData,
        $Table = layui.crazyQuery,
        $crazyTool = layui.crazyTool,
        layer = layui.layer

    let gMainTable = {};
    const defaultConfig = {
        field: undefined,
        title: undefined, // 可以直接是字符串，也可以是function
        rowField: undefined, // 这个是字段名，表示提示的是当前行的这个字段。优先顺序是先title，然后才是该字段
        duration: 2000, // 自动关闭时间，默认2000ms，单位是ms。0表示不关闭
        delay: 500, // 鼠标悬停多久时间后进入tips
        color: "#7c7c7c", // tips 背景色
    };
    let gConfigs = [];

    const classInit = {
        render: function () {
            this.config();
        },
        config: function () {
            $.each(gMainTable.cols[0], function (iRow, row) {
                if (row.hasOwnProperty('tips') && row.hasOwnProperty('field')) {
                    let c = {};
                    $.extend(c, defaultConfig, row.tips);
                    c.field = row.field;

                    gConfigs.push(c);
                }
            });
            console.log('crazy Tips Configs', gConfigs);
        },
    };

    const classIns = {
        render: function (myTable) {
            gMainTable = myTable;
            classInit.render();

            this.mouseover();
        },
        mouseover: function () {
            let othis = this;
            let trs = $Table.getTrs();
            $.each(gConfigs, function (i, c) {
                let field = c.field;

                $.each(trs, function (iRow, tr) {
                    let index = $(tr).data('index'); // 获取每一行的序号，LAY_TABLE_INDEX（这个是layui自带的参数），下标从0开始
                    let td = $Table.getTd(field, index);// 获取field列中第index行（即单元格）
                    let value = $Data.getCell(index, field); // 获取当前单元格值
                    let row = $Data.getRow(index);

                    let title = (typeof c.title === 'function') ? c.title(row) : c.title;
                    if (!title && !!c.rowField && row.hasOwnProperty(c.rowField)) {
                        title = row[c.rowField]
                    }
                    if (!!title) {
                        $(td).children(TABLE_CELL).attr('data-tips', title);
                        mouseoverEach(td, c);
                    }
                });
            })
        },
    };

    const mouseoverEach = (cell, config) => {
        let title = $(cell).children(TABLE_CELL).attr('data-tips');
        $crazyTool.mouseover($(cell), title, config);
    };

    //输出接口
    exports(MOD_NAME, classIns);
});